package com.sizu.aop;

import com.alibaba.fastjson.JSON;
import com.sizu.annotation.Log;
import com.sizu.common.entity.LogEntity;
import com.sizu.common.vo.ResultEntity;
import com.sizu.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class LogAop {

    @Autowired
    private LogService logService;

    @Pointcut(value = "execution(* com.sizu.web.*.*(..))")
    public void Pointcut(){};

    @AfterReturning(pointcut = "Pointcut()")
    public void after(JoinPoint joinPoint){
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Log annotation = method.getAnnotation(Log.class);
        if(null!=annotation){
            ServletRequestAttributes  servletRequestAttributes =
                    (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            LogEntity logEntity = new LogEntity();
            logEntity.setIp(request.getRemoteAddr());
            logEntity.setDesc(annotation.value());
            logEntity.setMenthodname(method.getName());
            logEntity.setPort(request.getServerPort()+"");
            logEntity.setUrl(request.getRequestURI());
            logEntity.setMethod(request.getMethod());
            ResultEntity add = logService.add(logEntity);
            log.info("----->{}", JSON.toJSONString(add));
        }
    }

}
